﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections;
using System.Diagnostics;
using Power.DataBridge;
using System.Configuration;
using System.Data.Common;
using SJHT_CustomerVoiceDownLoad.Models;
using System.Data.SqlClient;
using SJHT_CustomerVoiceDownLoad.Common;


namespace SJHT_CustomerVoiceDownLoad
{
    public partial class FromClient : Form
    {
        private int WriterByetNub = 52428800;//100M复制速度
        //源目标
        private FileStream FileToRead;
        //复制到文件
        private FileStream FileToWrite;
        //保存文件的地址
        private string SaveFile_Add;
        //源文件的名字
        private string File_Add;
        //设置正常写入字节
        private Byte[] byteToWrite;
        //设置剩余写入字节
        private Byte[] byteToLastWrite;
        //循环次数
        private long WriteTimes;
        //循环后的剩余字节
        private int L_Size;

        public FromClient()
        {
            InitializeComponent();// 初始化窗体内的控件
            this.datePickerYearAMouth.Value = DateTime.Now.Date.AddDays(-1);
        }

        #region 窗体加载

        //创建一个委托，是为访问TextBox控件服务的。
        public delegate void UpdateTxt(string msg);
        private delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            // InvokeRequired需要比较调用线程ID和创建线程ID
            // 如果它们不相同则返回true
            if (this.comboBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.comboBox1.Text = text;
            }
        }


        //定义一个委托变量
        public UpdateTxt updateTxt;

        //修改TextBox值的方法。
        public void UpdateTxtMethod(string msg)
        {
            this.showInfoLable.Text = msg;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FromClient_Load(object sender, EventArgs e)
        {
            //初始化配置文件
            //Config.init();
            Control.CheckForIllegalCrossThreadCalls = false;
            //初始化界面 FileSavePath
            this.fileSavePathTextBox.Text = Config.FileSavePath;
            this.typeRadioByYear.Checked = false;
            foreach (RadioButton radioButton in groupBox1.Controls.OfType<RadioButton>())
            {
                radioButton.CheckedChanged += radioButton_CheckedChanged;
            }
            //实例化界面更新委托
            updateTxt = new UpdateTxt(UpdateTxtMethod);
        }

        // 单选框事件
        void radioButton_CheckedChanged(object sender, EventArgs e)
        {
            loadListBtn.Text = (sender as RadioButton).Text;
        }
        #endregion

        #region 窗体关闭事件
        /// <summary>
        /// 窗体关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FromClient_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("是否关闭本系统？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information))
            {
                /*
                Application.Exit();//好像只在主线程可以起作用，而且当有线程，或是阻塞方法的情况下，很容易失灵
                this.Close();//只是关闭当前窗体。
                Application.ExitThread();//退出当前线程上的消息循环，并关闭该线程上的所有窗口。 也会失灵
                Environment.Exit(0); //前面三种方法都不能很好的退出程序，此方法可以完全退出程序，这个要强制得多。
                Process.GetCurrentProcess().Kill();//此方法完全奏效，绝对是完全退出
                System.Environment.Exit(0);
                */
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }
        #endregion

        #region 加载业务列表
        /// <summary>
        /// 加载业务列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void loadServiceListBtn_Click(object sender, EventArgs e) 
        {
            string phoneNo = this.phoneNotxtBox.Text.ToString().Trim();
            string serviceType = this.comboBox1.Text;
            if (string.IsNullOrEmpty(serviceType)|| serviceType=="请选择")
            {
                MessageBox.Show("请选择查询的分部！");
                return;
            }
            if (string.IsNullOrEmpty(phoneNo) || string.IsNullOrWhiteSpace(phoneNo))
            {
                MessageBox.Show("查询号码不能为空，请检查！");
                return;
            }
            this.BeginInvoke(updateTxt, "提取中......");
            //从控件中移除所有项和列（包括列表头）
            this.serviceListView.Clear();
            //设置样式
            this.serviceListView.GridLines = true;                              //显示表格线
            this.serviceListView.View = View.Details;                           //显示表格细节
            this.serviceListView.LabelEdit = false;                             //是否可编辑,ListView只可编辑第一列。
            this.serviceListView.Scrollable = true;                             //有滚动条
            this.serviceListView.HeaderStyle = ColumnHeaderStyle.Nonclickable;  //对表头进行设置
            this.serviceListView.FullRowSelect = true;                          //是否可以选择行 
            this.serviceListView.Activation = ItemActivation.OneClick;          //单击选中 
            this.serviceListView.CheckBoxes = true;
                        
            //添加表头
            this.serviceListView.Columns.Add("AC",35, HorizontalAlignment.Center);
            this.serviceListView.Columns.Add("ID",30, HorizontalAlignment.Center);
            this.serviceListView.Columns.Add("工号",70);
            this.serviceListView.Columns.Add("业务名", 160);
            this.serviceListView.Columns.Add("号码", 160);
            this.serviceListView.Columns.Add("外呼时间", 150);
            this.serviceListView.Columns.Add("录音路径", 300);
            //另起一个线程处理录音提取，避免界面卡死

            //线程的依附性：只有创建某些对象的线程、才能访问它所创建的某些对象
            //解决跨线程调用的问题，可以采用封送(Marshal) .调用Invoke方法
            //使用封送
            new Thread(() =>
            {
                //获取业务列表
                List<CC_VOICE> sList = getServiceList();
                if (sList == null || sList.Count == 0)
                {
                    MessageBox.Show("未查询到数据！");
                    return;
                }
                else
                {
                    MessageBox.Show("已查询到"+sList.Count.ToString()+"条数据！");
                }
                int loopInt = 1;
                //循环业务列表，写数据   
                foreach (CC_VOICE ccp in sList)
                {
                    Action<CC_VOICE> action = (data) =>
                    {
                        ListViewItem lvi = new ListViewItem();
                        lvi.SubItems.Add(loopInt.ToString());
                        lvi.SubItems.Add(ccp.xLine);
                        lvi.SubItems.Add(ccp.xActive);
                        lvi.SubItems.Add(ccp.xCalledPhone);
                        lvi.SubItems.Add(ccp.xDatetime.ToString());
                        lvi.SubItems.Add(ccp.xVocFileName);
                        this.serviceListView.Items.Add(lvi);
                        loopInt++;
                    };
                    Invoke(action, ccp);   
                }
            }).Start();
            //开始更新
            serviceListView.BeginUpdate();
            // this.BeginInvoke(updateTxt, "已完成数据查询！");
            // 结束更新
            serviceListView.EndUpdate();
        }
        #endregion

        # region 获取业务列表

        /// <summary>
        /// 获取业务列表
        /// </summary>
        /// <returns></returns>
        public List<CC_VOICE> getServiceList()
        {
            string phoneNo = this.phoneNotxtBox.Text.ToString().Trim();
            string serviceType = this.comboBox1.Text.ToString().Trim();
            string tableTime = "";
            string ConnStr = "";
            int DbType = Config.DbType;
            string RadioButtonName = this.loadListBtn.Text.ToString().Trim();
            List<CC_VOICE> lists = new List<CC_VOICE>();
            string Sql = "";
            if (RadioButtonName == "按年份查询:")
            {
                for (int i = 1; i < 13; i++)
                {
                    tableTime = this.dateTimePickerYear.Value.ToString("yyyy");
                    if (i < 10)
                    {
                        tableTime = tableTime + "0" + i.ToString();
                    }
                    else
                    {
                        tableTime = tableTime +i.ToString();
                    }
                    if (serviceType == "沙文总部")
                    {
                        Sql = " SELECT SeatCode AS xLine,PhoneNO AS xCalledPhone,ServiceName AS xActive,VoiceFilePath AS xVocFileName," +
                            "AddTime  AS xDatetime  FROM [CTIMS_V3_ARC].[dbo].[Cti_CallLogAndCheck_"+ tableTime +"] " +
                                " WHERE PhoneNO= '" + phoneNo + "'";
                        ConnStr = Config.ConnShaWenStr;
                    }
                    else
                    {
                         Sql = " SELECT xLine,xCalledPhone,xActive,xVocFileName,xDatetime " +
                                " FROM [CallCenterBack].[dbo].[XCALLCENTERLOGLAST" + tableTime + "] " +
                                " WHERE xCalledPhone= '" + phoneNo + "'";
                        ConnStr = Config.ConnStr;
                    }
                    try
                    {
                        List<CC_VOICE> list = DataCommon<CC_VOICE>.SelCommon(DbType, ConnStr, Sql);
                        foreach (var temp in list)
                        {
                            lists.Add(temp);
                        }
                    }
                    catch (Exception ex)
                    {
                        // MessageBox.Show("在连接数据库过程中发生异常，请检查！" + ex);
                        continue;
                    }  
                }
                return lists;
            }
            else
            {
                tableTime = this.datePickerYearAMouth.Value.ToString("yyyyMM");
                if (serviceType == "沙文总部")
                {
                    Sql = "SELECT SeatCode AS xLine,PhoneNO AS xCalledPhone,ServiceName AS xActive,VoiceFilePath AS xVocFileName," +
                            "AddTime  AS xDatetime  FROM [CTIMS_V3_ARC].[dbo].[Cti_CallLogAndCheck_" + tableTime + "] " +
                            " WHERE PhoneNO= '" + phoneNo + "'";
                    ConnStr = Config.ConnShaWenStr;
                }
                else
                {
                    Sql = "SELECT xLine,xCalledPhone,xActive,xVocFileName,xDatetime " +
                           "FROM [CallCenterBack].[dbo].[XCALLCENTERLOGLAST" + tableTime + "] " +
                           "WHERE xCalledPhone= '" + phoneNo + "'";
                    ConnStr = Config.ConnStr;
                }
                try
                {
                    List<CC_VOICE> list = DataCommon<CC_VOICE>.SelCommon(DbType, ConnStr, Sql);
                    return list;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("在连接数据库过程中发生异常，请检查！" + ex);
                    return null;
                }
                //sb.Append(Sql);
            }
        }
        #endregion

        #region  配置文件相关

        private void tabPage2_Click(object sender, EventArgs e)
        {

        }
        //加载配置
        private void loadSetBtn_Click(object sender, EventArgs e)
        {
            if (this.radioBtnConSW.Checked == true)
            {
                this.DBConnRichTextBox.Text = Config.ConnShaWenStr;
                this.ServerIPtextBox.Text = Config.SysShaWenIP;
                this.ServerUserNameTextBox.Text = Config.SysShaWenUser;
                this.ServerPwdTextBox.Text = Config.SysShaWenPwd;
                this.ServerPathTextBox.Text = Config.SysPath;
                this.IsWriteLogCheckBox.Checked = Config.IsLog;
                this.logFilePathTextBox.Text = Config.LogPath;
                this.IsSendSMSCheckBox.Checked = Config.IsSendSMS;
                this.SendSMSPhoneTextBox.Text = Config.SendSMSPhone;
            }
            else if (this.radioBtnConQXY.Checked == true)
            {
                this.DBConnRichTextBox.Text = Config.ConnStr;
                this.ServerIPtextBox.Text = Config.SysIP;
                this.ServerUserNameTextBox.Text = Config.SysUser;
                this.ServerPwdTextBox.Text = Config.SysPwd;
                this.ServerPathTextBox.Text = Config.SysPath;
                this.IsWriteLogCheckBox.Checked = Config.IsLog;
                this.logFilePathTextBox.Text = Config.LogPath;
                this.IsSendSMSCheckBox.Checked = Config.IsSendSMS;
                this.SendSMSPhoneTextBox.Text = Config.SendSMSPhone;

            }
            else
            {
                MessageBox.Show("请选择加载的配置类型！");
            }
        }
        //隐藏配置文件
        private void cleanShowSetInfoBtn_Click(object sender, EventArgs e)
        {
            this.DBConnRichTextBox.Text = "";
            this.ServerIPtextBox.Text = "";
            this.ServerUserNameTextBox.Text = "";
            this.ServerPwdTextBox.Text = "";
            this.ServerPathTextBox.Text = "";
            this.IsWriteLogCheckBox.Checked = false;            
            this.logFilePathTextBox.Text = "";
            this.IsSendSMSCheckBox.Checked = false;
            this.SendSMSPhoneTextBox.Text = "";
        }

        //保存配置
        private void saveSetBtn_Click(object sender, EventArgs e)
        {
            string nowConn = this.DBConnRichTextBox.Text;
            string nowUser = this.ServerUserNameTextBox.Text;
            string nowPwd = this.ServerPwdTextBox.Text;
            string nowIP = this.ServerIPtextBox.Text;
            string nowVoicePath = this.ServerPathTextBox.Text;
            if (string.IsNullOrEmpty(nowConn) || string.IsNullOrEmpty(nowVoicePath) || string.IsNullOrEmpty(nowUser) || string.IsNullOrEmpty(nowPwd) || string.IsNullOrEmpty(nowIP))
            {
                MessageBox.Show("请先加载配置信息");
                return;
            }
            if (this.radioBtnConSW.Checked == true)
            {
                Config.ConnShaWenStr = this.DBConnRichTextBox.Text;
                Config.UpdateConnectionStringsConfig("ConnShaWenStr", Config.ConnShaWenStr);

                Config.SysShaWenIP = this.ServerIPtextBox.Text;
                Config.UpdateConnectionStringsConfig("SysShaWenIP", Config.SysShaWenIP);

                Config.SysShaWenUser = this.ServerUserNameTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysShaWenUser", Config.SysShaWenUser);

                Config.SysShaWenPwd = this.ServerPwdTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysShaWenPwd", Config.SysShaWenPwd);

                Config.SysPath = this.ServerPathTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysPath", Config.SysPath);

                Config.IsLog = this.IsWriteLogCheckBox.Checked;
                Config.UpdateConnectionStringsConfig("IsLog", Convert.ToString(Config.IsLog));

                Config.LogPath = this.logFilePathTextBox.Text;
                Config.UpdateConnectionStringsConfig("LogPath", Config.LogPath);

                Config.IsSendSMS = this.IsSendSMSCheckBox.Checked;
                Config.UpdateConnectionStringsConfig("IsSendSMS", Convert.ToString(Config.IsSendSMS));

                Config.SendSMSPhone = this.SendSMSPhoneTextBox.Text;
                Config.UpdateConnectionStringsConfig("SendSMSPhone", Config.SendSMSPhone);

                MessageBox.Show("保存成功！");
            }
            else 
            {
                Config.ConnStr = this.DBConnRichTextBox.Text;
                Config.UpdateConnectionStringsConfig("ConnStr", Config.ConnStr);

                Config.SysIP = this.ServerIPtextBox.Text;
                Config.UpdateConnectionStringsConfig("SysIP", Config.SysIP);

                Config.SysUser = this.ServerUserNameTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysUser", Config.SysUser);

                Config.SysPwd = this.ServerPwdTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysPwd", Config.SysPwd);

                Config.SysPath = this.ServerPathTextBox.Text;
                Config.UpdateConnectionStringsConfig("SysPath", Config.SysPath);

                Config.IsLog = this.IsWriteLogCheckBox.Checked;
                Config.UpdateConnectionStringsConfig("IsLog", Convert.ToString(Config.IsLog));

                Config.LogPath = this.logFilePathTextBox.Text;
                Config.UpdateConnectionStringsConfig("LogPath", Config.LogPath);

                Config.IsSendSMS = this.IsSendSMSCheckBox.Checked;
                Config.UpdateConnectionStringsConfig("IsSendSMS", Convert.ToString(Config.IsSendSMS));

                Config.SendSMSPhone = this.SendSMSPhoneTextBox.Text;
                Config.UpdateConnectionStringsConfig("SendSMSPhone", Config.SendSMSPhone);

                MessageBox.Show("保存成功！");
            }
            //由于Properties范围为“用户”，所以这里也要更新一下配置，
            //避免再点加载时还是用原始没有变更过的值。 
            //配置保存到文件
            //Properties.Settings.Default.ConnStr = this.DBConnRichTextBox.Text;
            //Properties.Settings.Default.SysIP = this.ServerIPtextBox.Text;
            //Properties.Settings.Default.SysUser = this.ServerUserNameTextBox.Text;
            //Properties.Settings.Default.SysPwd  = this.ServerPwdTextBox.Text;
            //Properties.Settings.Default.SysPath  = this.ServerPathTextBox.Text;
            //Properties.Settings.Default.IsLog = this.IsWriteLogCheckBox.Checked; 
            //Properties.Settings.Default.LogPath = this.logFilePathTextBox.Text;
            //Properties.Settings.Default.IsSendSMS = this.IsSendSMSCheckBox.Checked;
            //Properties.Settings.Default.SendSMSPhone = this.SendSMSPhoneTextBox.Text;
            //Properties.Settings.Default.Save();
            
        }
        #endregion

        #region   测试登录 
        /// <summary>
        /// 测试登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void testLoginBtn_Click(object sender, EventArgs e)
        { 
            string nowUser = this.ServerUserNameTextBox.Text;
            string nowPwd = this.ServerPwdTextBox.Text;
            string nowIP = this.ServerIPtextBox.Text;

            //如果信息为空直接退出
            if (string.IsNullOrEmpty(nowUser) || string.IsNullOrEmpty(nowPwd) || string.IsNullOrEmpty(nowIP)) 
            {
                MessageBox.Show("请先加载配置信息");
                return;
            }
            FileCopy rfc = new FileCopy();
            FileCopy.isImpersonated = false;
            try
            {
                if (rfc.ImpersonateValidUser(nowUser, nowIP, nowPwd))
                {
                    string remoteFilePath = @"\\" + nowIP + @"\C$";  
                    Directory.GetCreationTime(remoteFilePath); 
                    MessageBox.Show("登录成功！");
                }
                rfc.UndoImpersonation();
            }
            catch (DirectoryNotFoundException)
            {
                MessageBox.Show("登录失败！");
            }
            finally
            {
                if (FileCopy.isImpersonated)
                    rfc.UndoImpersonation();
            }
        }
        #endregion

        #region 文件拷贝

        private bool CopyFiles(string File_Add,string SaveFile_Add)
        {
            try
            {
                label_Add.Text = "源地址:";

                label_Cpy_Add.Text = "复制到";

                label_Cpy_Lc.Text = "复制进程:";

                label_Write.Text = "已经写入:";

                label_FileSize.Text = "源文件总大小:";
                /*
                //文件选取
                OpenFileDialog openfileDialog = new OpenFileDialog();
                //show文件选取器
                openfileDialog.ShowDialog();

                File_Add = openfileDialog.FileName;
                */
                label_Add.Text += "：" + File_Add;

                //保存地址选取
                /*
                FolderBrowserDialog savefileDialog = new FolderBrowserDialog();

                savefileDialog.ShowDialog();

                SaveFile_Add = savefileDialog.SelectedPath;
                */
                label_Cpy_Add.Text += "：" + SaveFile_Add ;

                FileToRead = new FileStream(File_Add, FileMode.Open, FileAccess.Read);

                FileToWrite = new FileStream(SaveFile_Add, FileMode.OpenOrCreate, FileAccess.ReadWrite);

                label_FileSize.Text = "源文件总大小" + (FileToRead.Length / 1024).ToString() + "KB";
                if (FileToRead.Length > WriterByetNub)
                //设置写入字节数组
                {
                    byteToWrite = new byte[WriterByetNub];
                    //循环次数
                    WriteTimes = FileToRead.Length / WriterByetNub;
                    //多次循环后剩余字节
                    L_Size = Convert.ToInt32(FileToRead.Length % WriterByetNub);
                    //多次循环后字节数组
                    byteToLastWrite = new byte[L_Size];

                    for (long i = 0; i <= WriteTimes; i++)
                    {
                        //读源文件
                        FileToRead.Read(byteToWrite, 0, WriterByetNub);

                        //写数据到目标文件
                        FileToWrite.Write(byteToWrite, 0, WriterByetNub);

                        //设置进度条的值
                        progressBar.Value = Convert.ToInt32(i * 100 / WriteTimes);

                        Application.DoEvents();

                        //设置Lable上的进度值
                        label_Cpy_Lc.Text = "复制进程:" + Convert.ToInt32((i * 100) / WriteTimes).ToString() + "%";

                        //设置写入值
                        label_Write.Text = "已写入:" + (FileToRead.Position / 1024).ToString() + "KB";
                    }

                    //剩余字节的读和写
                    if (L_Size != 0)
                    {
                        FileToRead.Read(byteToLastWrite, 0, L_Size);

                        FileToWrite.Write(byteToLastWrite, 0, L_Size);
                    }
                }
                else
                {
                    progressBar.Maximum = (int)FileToRead.Length;
                    byteToWrite = new byte[FileToRead.Length];
                    FileToRead.Read(byteToWrite, 0, (int)FileToRead.Length);
                    label_Cpy_Lc.Text = "复制进程:" + Convert.ToInt32(FileToRead.Position / FileToRead.Length * 100).ToString() + "%";

                    //设置写入值
                    label_Write.Text = "已写入:" + (FileToRead.Position / 1024).ToString() + "KB";
                    progressBar.Value = (int)FileToRead.Position;
                    FileToWrite.Write(byteToWrite, 0, (int)FileToRead.Length);
                }
                FileToRead.Flush();

                FileToWrite.Flush();

                FileToRead.Close();

                FileToWrite.Close();
                return true;
                // MessageBox.Show("复制完成");
            }
            catch (Exception ex)

            {
                if (FileToRead != null)
                {
                    FileToRead.Flush();
                    FileToRead.Close();
                }
                if (FileToWrite!=null)
                {
                    FileToWrite.Flush();
                    FileToWrite.Close();
                }
                MessageBox.Show(ex.ToString());
                return false;

            }
        }

        /// <summary>
        /// 根据提供的文件列表进行文件拷贝
        /// </summary>
        /// <param name="vList"></param>
        /// <param name="isTransToWav"></param>
        /// <param name="isDeleteVox"></param>
        public void voiceFileCopy(List<CC_VOICE> vList, Boolean isTransToWav, Boolean isDeleteVox)
        {
            int succCnt = 0;
            Boolean fileIsExist = false;

            //登录录音文件服务器
            FileCopy rfc = new FileCopy();
            FileCopy.isImpersonated = false;
            string serviceType = this.comboBox1.Text.ToString().Trim();
            string SysUser = "";
            string SysIP = "";
            string SysPwd = "";
            if (serviceType == "沙文总部")
            {
                SysUser = Config.SysShaWenUser;
                SysIP = Config.SysShaWenIP;
                SysPwd = Config.SysShaWenPwd;
            }
            else
            {
                SysUser = Config.SysUser;
                SysIP = Config.SysIP;
                SysPwd = Config.SysPwd;
            }
            try
            {
                if (rfc.ImpersonateValidUser(SysUser, SysIP,SysPwd))
                {
                    FileCopy.isImpersonated = true;

                    try
                    {
                        //检查本地目录，没有的话创建一个
                        if (!Directory.Exists(this.fileSavePathTextBox.Text))
                        {
                            Directory.CreateDirectory(@"" + this.fileSavePathTextBox.Text);
                        }

                        int fIndex = 0;

                        //逐个拷贝
                        foreach (CC_VOICE f in vList)
                        {
                            fIndex++;
                            fileIsExist = false;

                            //遍历提供的磁盘,找到文件所在
                            string serverFilePath = f.xVocFileName;
                            string relist = "";
                            string[] diskList = serverFilePath.Split(new char[1] { '\\' });
                            string nowServerFilePath = "";
                            // d:\callvoice\20120428\129\018084205739_141636.vox
                            //\\10.2.1.171\h\贵州省\201610\20161027\1636\17848582_1636_13847016526_20161027_094400_41.mp3
                            // D:\phone\recordb\151748_1408_18302609612_20170802_143019_7.mp3
                            if (this.comboBox1.Text == "沙文总部")
                            {
                                string[] pathList = diskList[diskList.Length - 1].Split(new char[1] { '_' });
                                relist = pathList[3];
                                //relist =  @"VoiceFiles\" + relist;
                                string yearandmonth = pathList[3].Substring(0, 6);
                                nowServerFilePath = @"\\" + SysIP + @"\" +@"\h\贵州省\"+ yearandmonth+@"\"+relist + @"\" + pathList[1] + @"\" + diskList[diskList.Length - 1];
                            }
                            else
                            {
                                relist = getDirectory(diskList[2]);
                                if (string.IsNullOrEmpty(relist))
                                {
                                    MessageBox.Show("未查到录音所在文件夹，请检查（仅支持2015年5月27日以后的号码）！");
                                    return;
                                }
                                else
                                {
                                    nowServerFilePath = @"\\" +SysIP + @"\" + relist + "\\" + diskList[2] + @"\" + diskList[3] + "\\" + diskList[4];
                                }
                            }
                            
                            if (File.Exists(@nowServerFilePath))
                            {
                                serverFilePath = @nowServerFilePath;
                                fileIsExist = true;

                            }
                            if (!fileIsExist)
                                break;
                            string subDirStr = "";
                            //如果目标目录不存在，先创建目录
                            string localDirPath = @"" + this.fileSavePathTextBox.Text + subDirStr;
                            if (!Directory.Exists(localDirPath))
                            {
                                Directory.CreateDirectory(localDirPath);
                            }
                            //生成本地路径
                            string localFilePath = @"" + this.fileSavePathTextBox.Text + subDirStr + serverFilePath.Substring(serverFilePath.LastIndexOf("\\"));

                            //进行文件拷贝
                            this.BeginInvoke(updateTxt, "提取文件 " + fIndex.ToString() + "/" + vList.Count.ToString() + "  " + @"" + serverFilePath + "...");

                            //拷贝文件
                            var coprResult=CopyFiles(serverFilePath, localFilePath);
                            if (coprResult)
                            {
                                succCnt++;
                                if (Config.IsLog)
                                {
                                    LogFile.Write("提取文件：" + @"" + serverFilePath + "成功！");
                                }
                                //文件转换
                                if (isTransToWav)
                                {
                                    this.BeginInvoke(updateTxt, "转换文件 " + fIndex.ToString() + "/" + vList.Count.ToString() + "  " + localFilePath + " 为mp3文件. ");
                                    VoiceTrans.PcmtoWave(@"" + localFilePath, @"" + localFilePath.Replace(".vox", ".mp3"));
                                    if (Config.IsLog)
                                    {
                                        LogFile.Write("转换文件：" + @"" + localFilePath + "成功！");
                                    }
                                    //文件删除
                                    if (isDeleteVox)
                                    {
                                        File.Delete(@"" + localFilePath);
                                    }
                                    if (Config.IsLog)
                                    {
                                        LogFile.Write("删除文件：" + @"" + localFilePath + "成功！");
                                    }
                                }
                            }
                            //File.Copy(serverFilePath, localFilePath, true);
                            
                        //this.showInfoLable.Text = "录音提取完毕！";
                        this.BeginInvoke(updateTxt, "录音提取完毕！");
                        MessageBox.Show("录音提取完毕！数量：" + succCnt);
                        }
                    }
                    catch (IOException)
                    {
                        MessageBox.Show("在拷贝文件时，登录失败或者目录不存在！");
                    }
                }
            }
            finally
            {
                if (FileCopy.isImpersonated)
                    rfc.UndoImpersonation();
            }
        }
        #endregion

        #region  录音操作
        /// <summary>
        /// 录音提取并保存
        /// </summary>
        public void voiceFileSaveByList(List<CC_VOICE> vList)
        {  
            if (Config.IsLog)
            {
                LogFile.Write("获取文件列表，文件数量：" + vList.Count);
            }
            //根据录音记录进行路由文件拷贝            
            Boolean isTransToWav = false;
            Boolean isDeleteVox = false;
            if (this.tranToWavCheckBox.Checked)
            {
                isTransToWav = true;
                isDeleteVox = true;
            }
            voiceFileCopy(vList, isTransToWav, isDeleteVox);
        }
         
        /// <summary>
        /// 录音提取按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void voiceFileSaveBtn_Click(object sender, EventArgs e)
        {
            //提取录音类型 
            int getTypeInt=2;
            if (this.typeRadioByYear.Checked)
            {
                getTypeInt = 2;
            }
            if (getTypeInt == 0)
            {
                MessageBox.Show("请选择录音的提取类型！");
                return;
            }

            //选中的业务列表
            List<CC_VOICE> vList = new List<CC_VOICE>();
            CC_VOICE parm0 = new CC_VOICE();
            if (this.serviceListView.CheckedItems.Count > 0)
            {
                for (int i = 0; i < this.serviceListView.Items.Count; i++)
                {
                    if (this.serviceListView.Items[i].Checked)
                    {
                        parm0.xActive = this.serviceListView.Items[i].SubItems[3].Text;
                        parm0.xCalledPhone = this.serviceListView.Items[i].SubItems[4].Text;
                        parm0.xDatetime = Convert.ToDateTime(this.serviceListView.Items[i].SubItems[5].Text);
                        parm0.xVocFileName = this.serviceListView.Items[i].SubItems[6].Text;
                        break;
                    }
                }
            }
            vList.Add(parm0);
            //另起一个线程处理录音提取，避免界面卡死
            Thread objThread = new Thread(new ThreadStart(delegate
            {
                voiceFileSaveByList(vList);
            }));
            objThread.Start();            
        }
        

        /// <summary>
        /// 选择录音保存路径按钮（单击事件处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectSavePathBtn_Click(object sender, EventArgs e)
        {
            if (this.fileSavefolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string nowPath = fileSavefolderBrowserDialog.SelectedPath;
                this.fileSavePathTextBox.Text = nowPath;

                //同步保存到配置
                Config.FileSavePath = nowPath;
                Properties.Settings.Default.FileSavePath = nowPath;
                Properties.Settings.Default.Save();
            }
        }

        /// <summary>
        /// 打开录音保存路径按钮（单击事件处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openSavePathBtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.fileSavePathTextBox.Text.ToString().Trim()))
            {
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
                psi.Arguments = "/e,/root," + this.fileSavePathTextBox.Text;
                System.Diagnostics.Process.Start(psi);
            }
            else
            {
                MessageBox.Show("录音保存目录为空！");
            }
        }

        #endregion

        #region  日志操作
        /// <summary>
        /// 选择日志保存路径（单击事件处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectLogFilePathBtn_Click(object sender, EventArgs e)
        {
            if (fileSavefolderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                string nowPath = fileSavefolderBrowserDialog.SelectedPath;
                this.logFilePathTextBox.Text = nowPath;
            }
        }
        /// <summary>
        /// 打开日志保存路径按钮（单击事件处理）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void viewLogBtn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Config.LogPath))
            {
                System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("Explorer.exe");
                psi.Arguments = "/e,/root," + Config.LogPath;
                System.Diagnostics.Process.Start(psi);
            }
            else
            {
                MessageBox.Show("日志保存目录为空！");
            }

        }
        #endregion

        #region  文件夹-文件名处理
        /*
         * 获得指定路径下所有文件名
         * string path      文件路径
         * int indent       输出时的缩进量
         */
        public static List<string> getFileName(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            List<string> scoreList = new List<string>();//创建了一个空列表
            foreach (FileInfo f in root.GetFiles())
            {
                scoreList.Add( f.Name);
            }
            return scoreList;
        }

        //获得指定路径下所有子目录名
        public static string getDirectory(string path)
        {
            string[] dicPaths = new string[]{"20150527 - 20150724",
                                            "20150725-20150820",
                                            "20150821-20150918",
                                            "20150919-20151023",
                                            "20151024-20151206",
                                            "20151207-20160317",
                                            "20160318-20160626",
                                            "20160627-20161020",
                                            "20161021-20180107" };
            string outpath = "";
            int intpath = int.Parse(path);
            foreach ( string dicPath in dicPaths)
            {
               string[] checkValue = dicPath.Split(new char[1] { '-' });
                if (intpath >= int.Parse(checkValue[0]) && intpath <= int.Parse(checkValue[1]))
                {
                    outpath = dicPath;
                }
            }
            return outpath;
        }
        #endregion

    }
}
